import { pageList, IPageListParams, del, IDelParams } from '@/api/commonInstance'
import { DBNames } from '@/enum/dbName'

export default (templateName: string) => {
  const mixin = {
    data() {
      return {
        templateName: DBNames[templateName],
        loading: false,
        searchStr: '',
        dataList: [],
        total: 0,
        selected: [],
        conditions: {},
        pagination: {
          pageNum: 1,
          pageSize: 10,
        },
      }
    },
    created() {
      // @ts-ignore
      this.fetchData()
    },
    methods: {
      async del(id: string) {
        const { templateName } = this as any
        const params: IDelParams = {
          id,
          templateName,
        }
        await del(params)
        // @ts-ignore
        this.$message.success('删除成功!')
        this.fetchData()
      },

      async fetchData() {
        const {
          templateName,
          conditions,
          pagination: { pageNum, pageSize },
        } = this as any

        const params: IPageListParams = {
          conditions,
          sort: { updatedTime: -1 },
          pageInfo: { pageNum, pageSize },
          templateName,
        }

        // @ts-ignore
        this.loading = true
        // @ts-ignore
        const { list, total } = await pageList(params)
        // @ts-ignore
        this.dataList = list
        // @ts-ignore
        this.total = total
        // @ts-ignore
        this.$emit('update:dataList', list)
        // @ts-ignore
        this.$emit('update:total', total)
        // @ts-ignore
        this.loading = false
      },

      edit(id: string) {
        // @ts-ignore
        this.$refs.addEdit?.open(2, id)
      },

      handleSelectionChange(val: string[]) {
        // @ts-ignore
        this.selected = val
      },

      handleAdd() {
        // @ts-ignore
        this.$refs.addEdit?.open()
      },

      handleSearch(val: string) {
        // @ts-ignore
        this.pagination.pageNum = 1
        // @ts-ignore
        this.conditions['data.name'] = { $regex: val }
        // @ts-ignore
        this.fetchData()
      },

      getFirstImage(row: any) {
        return (
          (row.data.imgList && row.data.imgList[0] && row.data.imgList[0].url) ||
          'https://fakeimg.pl/42x42/'
        )
      },
    },
  }
  return mixin
}
